package com.wooming.myserver.controller;

import com.wooming.myserver.dto.HeadshotDTO;
import com.wooming.myserver.entity.User;
import com.wooming.myserver.service.inter.HeadshotService;
import com.wooming.myserver.service.inter.UserService;
import com.wooming.myserver.util.ApiObserver;
import com.wooming.myserver.util.Result;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.nio.file.Files;
import java.nio.file.Path;

/**
 * 头像管理API控制器
 *
 * @author wooming 2025/05/22
 */
@RestController
public class HeadshotController {
    // 头像存储根路径
    private final Path root = Path.of("headshots");

    // 依赖项
    private HeadshotService headshotService;
    private UserService userService;

    // 注入依赖项
    @Autowired
    public void setHeadshotService(
            HeadshotService headshotService,
            UserService userService
    ) {
        this.headshotService = headshotService;
        this.userService = userService;
    }

    @PostMapping("/api/upload")
    public Result<?> upload(@RequestParam("file") MultipartFile file,
                            @RequestHeader("Authorization") String authorization
    ) {
        // 监控API调用
        Result<?> result = ApiObserver.observe("头像上传");
        if (result.getCode() != 200) return result;

        // 获取jwt...残余,不改为妙,要改需要改一堆
        String jwt = authorization.substring(7);
        try {
            // 验证jwt
            User user = headshotService.verify(jwt);
            if (user == null) {
                return Result.error(401, "用户未登录");
            }

            // 创建上传目录
            if (!Files.exists(root)) {
                Files.createDirectories(root);
            }

            // 保存并替换文件
            HeadshotDTO headshotDTO = new HeadshotDTO(file, jwt);
            if (headshotService.upload(user, headshotDTO)) {
                // 返回成功信息
                return Result.success("上传成功");
            } else {
                // 返回失败信息
                return Result.error(400, "上传失败");
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return Result.error(500, "服务器错误");
        }
    }

    @GetMapping("/api/headshot")
    public Result<?> getHeadshot(
            HttpServletResponse response,
            @RequestHeader("Authorization") String authorization
    ) {
        // 监控API调用
        Result<?> result = ApiObserver.observe("头像获取");
        if (result.getCode() != 200) return result;

        // 获取jwt
        String jwt = authorization.substring(7);

        try {
            // 验证jwt
            User user = headshotService.verify(jwt);
            if (user == null) {
                return Result.error(401, "用户未登录");
            }

            // 建立连接,传输头像文件
            if (headshotService.sendHeadshot(response, user)) {
                return Result.success("获取成功");
            } else {
                return Result.error(400, "获取失败");
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return Result.error(500, "服务器错误");
        }
    }

    @GetMapping("/api/public/get")
    public Result<?> getHeadshot(
            HttpServletResponse response,
            @RequestParam("userId") Integer userId
    ) {
        System.out.println("有人访问公共头像获取接口");   //监控后端API调用

        try {
            User user = userService.findUser(userId);
            if (headshotService.sendHeadshot(response, user)) {
                return Result.success("获取成功");
            } else {
                return Result.error(400, "获取失败");
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return Result.error(500, "服务器错误");
        }
    }
}
